
package br.unifor.cct.mia.coevolution.evaluate;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.unifor.cct.mia.coevolution.InvalidTypeException;
import br.unifor.cct.mia.coevolution.memory.MemoryBuffer;
import br.unifor.cct.mia.coevolution.memory.MemoryIndividual;
import br.unifor.cct.mia.coevolution.memory.SharedMemory;
import br.unifor.cct.mia.dataenhancement.Database;
import br.unifor.cct.mia.dataenhancement.Structure;
import br.unifor.cct.mia.dataenhancement.Tuple;
import br.unifor.cct.mia.evaluate.classification.WekaClassification;
import br.unifor.cct.mia.evolutionary.Genotype;
import br.unifor.cct.mia.evolutionary.Individual;
import br.unifor.cct.mia.ga.Ga;

public class BestIndividualEvaluation {
	
	private static int resultCount = 0;
	
	public static double evaluate(Individual ind, int specieType, ArrayList species, MemoryBuffer atualMemory,
			Structure struc, Database db,Tuple tuples,List positions,String[] options, int nBits) throws IOException, InterruptedException, InvalidTypeException {
		
		double result = 0;
		
		resultCount++;
		String fileName = "temp/"+"result"+resultCount+".txt";
		
		File resultFile = new File(fileName);
		resultFile.delete();		
		resultFile = null;
		
		SharedMemory memoryAux = new SharedMemory();		
		MemoryIndividual mInd = new MemoryIndividual(ind,specieType, nBits);
		
		memoryAux.add(mInd);
		
		Ga ga = null;
		for (Iterator iter = species.iterator(); iter.hasNext();) {
			ga = (Ga) iter.next();
			
			if ( ga.getSpecieType().intValue() != specieType ) {
				if ( ga.population == null ) continue;
				int pos = ga.indexBestWorst[0];
				if ( ga.population[pos] == null ) continue;
				Individual gen = ga.population[pos];					
				MemoryIndividual individuo = new MemoryIndividual(gen,ga.getSpecieType().intValue(), nBits);
				memoryAux.add(individuo);
			}
		}
		
		
		resultFile = EvaluateUtils.memoryToFile(memoryAux,fileName,struc,db,tuples,positions, nBits);
		
		WekaClassification classificator = new WekaClassification(ga.getLearnerType(),options);
		result = classificator.evaluate(resultFile);
		
		((Genotype)ind).setFitness(result);
		memoryAux.setFitness(result);
		
		atualMemory.add(memoryAux);
		
		resultFile.delete();		
		
		return result;
	}
	
}
